package org.sean.framework.redis;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.data.redis.serializer.RedisSerializer;

/**
 * 使用Fastjson处理的 Redis编码类
 * Date: 2018/10/1 17:50
 *
 * @param <V> V
 * @author Sean.xie
 */
public class ObjectRedisSerializer<V> implements RedisSerializer<V> {

    private static ParserConfig defaultRedisConfig = new ParserConfig();

    static {
        defaultRedisConfig.setAutoTypeSupport(true);
    }

    /**
     * Creates a new {@link ObjectRedisSerializer}
     */
    public ObjectRedisSerializer() {
    }


    /**
     * 解码
     */
    @Override
    public V deserialize(byte[] bytes) {
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        return JSON.parseObject(new String(bytes), null, defaultRedisConfig);
    }

    /**
     * 编码
     */
    @Override
    public byte[] serialize(Object t) {
        if (t == null) {
            return new byte[0];
        }
        return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes();
    }

}
